import 'dart:async';

const Duration _kDuration = const Duration(milliseconds: 400);

class PreventRepeatedEvent {
  StreamController _controller = StreamController();
  StreamSubscription _subscription;
  Timer _timer;
  final Duration duration;

  PreventRepeatedEvent({this.duration = _kDuration});

  void addEventListener(void dataCall(dynamic data)) {
    if (!_controller.hasListener) {
      _subscription = _controller.stream.listen((event) {
        dataCall(event);
      });
    }
  }

  void sendEvent(dynamic data) {
    if (_timer != null) {
      _timer.cancel();
    }
    _timer = Timer(duration, () {
      if (_subscription != null) {
        _controller.add(data);
      }
    });
  }

  void cancel() {
    _subscription?.cancel();
    _subscription = null;
    _controller = StreamController();
  }

  void dispose() {
    _controller?.close();
    _subscription?.cancel();
    _subscription = null;
  }
}
